package com.gs.wechatdemo.activity;

import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.reflect.TypeToken;
import com.gs.wechatdemo.R;
import com.gs.wechatdemo.adapter.ChatAdapter;
import com.gs.wechatdemo.adapter.base.BaseAdapter;
import com.gs.wechatdemo.callback.CallbackWithProgress;
import com.gs.wechatdemo.constant.AllConstants;
import com.gs.wechatdemo.constant.ChatCode;
import com.gs.wechatdemo.control.CircleImageView;
import com.gs.wechatdemo.control.OnRecyclerViewScrollListener;
import com.gs.wechatdemo.db.bean.ChatBean;
import com.gs.wechatdemo.db.bean.ContactBean;
import com.gs.wechatdemo.db.dto.EventBean;
import com.gs.wechatdemo.db.dto.MsgContentDto;
import com.gs.wechatdemo.db.dto.MsgDto;
import com.gs.wechatdemo.db.dto.UserDto;
import com.gs.wechatdemo.db.sqlite.SQLiteUtil;
import com.gs.wechatdemo.service.SignalRService;
import com.gs.wechatdemo.signalr.SignalRCode;
import com.gs.wechatdemo.signalr.SignalRUtil;
import com.gs.wechatdemo.util.DateUtil;
import com.gs.wechatdemo.util.DensityUtil;
import com.gs.wechatdemo.util.FileUtils;
import com.gs.wechatdemo.util.GsonUtil;
import com.gs.wechatdemo.util.ImageUtil;
import com.gs.wechatdemo.util.OKHttpUtil;
import com.gs.wechatdemo.util.SPUtil;
import com.gs.wechatdemo.util.WindowUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ContactListActivity extends BaseListActivity<ContactBean> {

    private String myId;
    private ChatAdapter adapter;
    private TextView tvMyName;
    private CircleImageView ivMy;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_contact_list;
    }

    @Override
    protected void initView() {
        if (TextUtils.isEmpty(SPUtil.getInstance().getString(AllConstants.ID))) {
            toLogin();
            return;
        } else {
            startService(new Intent(ContactListActivity.this, SignalRService.class));
        }
        WindowUtil.setBarBgColor(this, R.color.color_ee);
        EventBus.getDefault().register(this);
        myId = SPUtil.getInstance().getString(AllConstants.ID);
        tvMyName = fd(R.id.tv_my);
        ivMy = fd(R.id.iv_my);
        recyclerView.addOnScrollListener(new OnRecyclerViewScrollListener() {
            @Override
            public void onBottom() {
                super.onBottom();
                loadData();
            }
        });
        adapter = new ChatAdapter(this, this, list, R.layout.rv_chat);
        adapter.setOnItemClickListener((v, position) -> {
            Intent intent = new Intent(ContactListActivity.this,BubbleActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(ContactListActivity.this, 0, intent, 0);

//            Intent intent = new Intent(ContactListActivity.this, ChatListActivity.class);
//            ContactBean dto = list.get(position);
//            intent.putExtra(AllConstants.OTHER_ID, dto.getUserOrGroupId());
//            startActivityForResult(intent, 1);
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setItemAnimator(null);
        recyclerView.setAdapter(adapter);

        findViewById(R.id.tv_logout).setOnClickListener(v -> {
            stopService(new Intent(ContactListActivity.this, SignalRService.class));
            SPUtil.getInstance().putString(AllConstants.ID, "");
            SQLiteUtil.getInstance().logout();
            toLogin();
        });

        List<ContactBean> queryList = SQLiteUtil.getInstance().queryContactList(offset + "," + limit);
        if (queryList.isEmpty()) {
            new Handler().postDelayed(() -> SignalRUtil.getInstance().send(SignalRCode.SEND_MSG, SignalRCode.TYPE_USER, "uses"), 500);
        } else {
            list.addAll(queryList);
            adapter.notifyDataSetChanged();
            offset = list.size();
            setMyInfo();
        }
    }

    private void setMyInfo() {
        ContactBean bean = SQLiteUtil.getInstance().queryContactById(myId);
        tvMyName.setText(bean.getName());
        ImageUtil.loadImg(this, bean.getPhoto(), ivMy);
    }

    private void toLogin() {
        Intent intent = new Intent(ContactListActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void loadData() {
        List<ContactBean> queryList = SQLiteUtil.getInstance().queryContactList(offset + "," + limit);
        if (!queryList.isEmpty()) {
            list.addAll(queryList);
            adapter.notifyDataSetChanged();
            offset = list.size();
        }
    }

    @Override
    protected void initData() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventBean event) {
        String msgType = event.getMsgType();
        if (msgType.equals(SignalRCode.TYPE_LOGIN) || msgType.equals(SignalRCode.TYPE_LOGOUT)) {
            return;
        }
        String msgJson = event.getMsg();
        if (msgType.equals(SignalRCode.TYPE_USER)) {
            MsgDto<List<UserDto>> msgDto = (MsgDto<List<UserDto>>) GsonUtil.getInstance().fromJson(msgJson, new TypeToken<MsgDto<List<UserDto>>>() {
            }.getType());
            List<UserDto> listGet = msgDto.getMsg();
            if (listGet != null && !listGet.isEmpty()) {
                for (int i = 0; i < listGet.size(); i++) {
                    UserDto userDto = listGet.get(i);
                    if (TextUtils.isEmpty(userDto.getPhoto())) {
                        addUserContact(userDto, "");
                        continue;
                    }
                    downloadPhoto(userDto);
                }
            }
            return;
        }
        if (event.isAdd()) {
            MsgDto<MsgContentDto> msgDto = (MsgDto<MsgContentDto>) GsonUtil.getInstance().fromJson(msgJson, new TypeToken<MsgDto<MsgContentDto>>() {
            }.getType());
            MsgContentDto msgDtoMsg = msgDto.getMsg();
            String toId = msgDtoMsg.getToId();
            String fromId = msgDtoMsg.getFromId();
            String content = msgDtoMsg.getContent();
            ContactBean contactBean;
            ChatBean chatBean = new ChatBean();
            if (toId.equalsIgnoreCase(myId)) {
                contactBean = SQLiteUtil.getInstance().queryContactById(fromId);
                chatBean.setChatId(fromId);
                isOvertime(contactBean.getDate(), fromId);
            } else {
                contactBean = SQLiteUtil.getInstance().queryContactById(toId);
                chatBean.setChatId(toId);
                chatBean.setGroupId(toId);
                isOvertime(contactBean.getDate(), toId);
            }
            contactBean.setNum(contactBean.getNum() + 1);
            chatBean.setUserId(fromId);
            chatBean.setPhoto(ImageUtil.getLocalPhoto(fromId));
            chatBean.setContent(content);
            switch (msgType) {
                case SignalRCode.TYPE_USER_WORD:
                case SignalRCode.TYPE_GROUP_WORD:
                    contactBean.setContent(content);
                    chatBean.setContent(content);
                    chatBean.setViewType(ChatCode.CHAT_OTHER_TEXT);
                    break;
                case SignalRCode.TYPE_USER_IMG:
                case SignalRCode.TYPE_GROUP_IMG:
                    contactBean.setContent("图片");
                    Bitmap bitmap = ImageUtil.base64ToBitmap(content);
                    String path = ImageUtil.saveBitmap(this, bitmap);
                    chatBean.setContent(path);
                    if (bitmap.getWidth() > DensityUtil.dp2px(120)) {
                        chatBean.setPhotoW(DensityUtil.dp2px(120));
                        chatBean.setPhotoH((int) (DensityUtil.dp2px(120) * ((float) bitmap.getHeight() / bitmap.getWidth())));
                    } else if (bitmap.getWidth() < DensityUtil.dp2px(10)) {
                        chatBean.setPhotoW(DensityUtil.dp2px(10));
                        chatBean.setPhotoH((int) (DensityUtil.dp2px(10) * ((float) bitmap.getWidth() / bitmap.getHeight())));
                    } else {
                        chatBean.setPhotoW(bitmap.getWidth());
                        chatBean.setPhotoH(bitmap.getHeight());
                    }
                    chatBean.setViewType(ChatCode.CHAT_OTHER_IMG);

                    break;
                case SignalRCode.TYPE_USER_VOICE:
                case SignalRCode.TYPE_GROUP_VOICE:
                    contactBean.setContent("语音");
                    String pathName = "demo_voice_" + DateUtil.DateTimeToStr(new Date(), "yyyyMMdd_hhmmss") + ".m4a";
                    String pathVoice = FileUtils.base64ToFile(this, content, pathName);
                    chatBean.setContent(pathVoice);
                    chatBean.setViewType(ChatCode.CHAT_OTHER_VOICE);
                    break;
            }
            Date date = new Date();
            contactBean.setDate(date);
            chatBean.setDate(date);
            SQLiteUtil.getInstance().updateContact(contactBean);
            refreshData();
            SQLiteUtil.getInstance().insertChat(chatBean);
        }
    }

    private void isOvertime(Date date, String userId) {
        if (DateUtil.isOvertime(date)) {
            ChatBean bean = new ChatBean();
            bean.setChatId(userId);
            bean.setViewType(ChatCode.CHAT_TIME);
            bean.setDate(new Date());
            SQLiteUtil.getInstance().insertChat(bean);
        }
    }

    private void refreshData() {
        list.clear();
        offset = 0;
        loadData();
    }


    private void downloadPhoto(UserDto userDto) {
        // 显示一张图片
        if (userDto.getLevel() == 1) {
            OKHttpUtil.getInstance().downloadFile(null, 0, userDto, OKHttpUtil.IMG_URL + userDto.getPhoto(), FileUtils.getInstance().createFile(this, "photo_" + userDto.getId() + ".jpg"), new CallbackWithProgress() {
                @Override
                public void onSuccess(Object obj, UserDto userDto, List<String> imgList, int length) {
                    File photo = (File) obj;
                    addUserContact(userDto, photo.getAbsolutePath());
                    if (userDto.getId().equalsIgnoreCase(myId)) {
                        tvMyName.setText(userDto.getUserName());
                        ImageUtil.loadImg(ContactListActivity.this, photo.getAbsolutePath(), ivMy);
                    }
                }

                @Override
                public void onFailed(Exception e, UserDto userDto) {
                    addUserContact(userDto, "");
                }

                @Override
                public void onProgress(int progress) {

                }
            });
        } else { // 显示图片组
            List<String> imgList = new ArrayList<>();
            String[] split = userDto.getPhoto().split(",");
            for (int i = 0; i < split.length; i++) {
                OKHttpUtil.getInstance().downloadFile(imgList, split.length, userDto, OKHttpUtil.IMG_URL + split[i], FileUtils.getInstance().createFile(this, "photo_" + userDto.getId() + i + ".jpg"), new CallbackWithProgress() {
                    @Override
                    public void onSuccess(Object obj, UserDto userDto, List<String> imgList, int length) {
                        File photo = (File) obj;
                        imgList.add(photo.getAbsolutePath());
                        if (imgList.size() == length) {
                            StringBuilder img = new StringBuilder();
                            for (String s : imgList) {
                                img.append(",").append(s);
                            }
                            addUserContact(userDto, img.substring(1));
                        }
                    }

                    @Override
                    public void onFailed(Exception e, UserDto userDto) {
                        addUserContact(userDto, "");
                    }

                    @Override
                    public void onProgress(int progress) {

                    }
                });
            }
        }
    }

    private void addUserContact(UserDto userDto, String photo) {
        ContactBean bean = new ContactBean();
        bean.setPhoto(photo);
        bean.setUserOrGroupId(userDto.getId());
        bean.setName(userDto.getUserName());
        bean.setLevel(userDto.getLevel());
        bean.setNum(0);
        bean.setDate(new Date());
        list.add(bean);
        adapter.notifyItemInserted(adapter.getItemCount() - 1);
        SQLiteUtil.getInstance().insertContact(bean);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            refreshData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}